/** BytePay TPDU 代理服务器
 *
 * Copyright (c) 2016 Lucky Byte, Inc.
 */
#include <locale.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <gio/gio.h>

static FILE      *log_file = NULL;
static GMainLoop *main_loop = NULL;
static GKeyFile  *ini_file = NULL;

static gchar *ini_path = "./etc/tpdu.ini";

/* 命令行选项定义
 */
static GOptionEntry entries[] =
{
    { "inifile", 'i', 0, G_OPTION_ARG_FILENAME, &ini_path,
      "配置文件路径，默认为'./etc/tpdu.ini'", "Path" },
};

/* 退出时关闭日志文件
 */
static void tpdu_close_logfile()
{
  if (log_file)
    {
      fclose(log_file);
      log_file = NULL;
    }
}

/* 日志输出处理函数
 */
static void tpdu_log_handler(const gchar    *log_domain,
                             GLogLevelFlags  log_level,
                             const gchar    *message,
                             gpointer        user_data)
{
  gchar timebuf[256];
  time_t t;
  gchar *log_path = user_data;
  if (!log_file)
    {
      log_file = fopen(log_path ? log_path : "/tmp/tpdu.log", "a");
      if (!log_file)
        {
          g_print("打开日志文件[%s]错误: %s\n", log_path, g_strerror(errno));
          exit(1);
        }
      atexit(tpdu_close_logfile);
    }
  time(&t);
  strftime(timebuf, sizeof(timebuf), "%F %T", localtime(&t));
  fprintf(log_file, "%s[%s] - %s\n", timebuf, log_domain, message);
  fflush(log_file);
}

/* 解析配置文件
 */
static gboolean tpdu_read_inifile()
{
  GError *error = NULL;
  if (!ini_path)
    {
      g_warning("未找到配置文件[%s]，请检查.", ini_path);
      return FALSE;
    }
  ini_file = g_key_file_new();
  if (!g_key_file_load_from_file(ini_file, ini_path,
                                 G_KEY_FILE_NONE, &error))
    {
      g_warning("读配置文件[%s]错误: %s", ini_path, error->message);
      g_error_free(error);
      return FALSE;
    }
  return TRUE;
}


/* 启动网络服务
 */
gboolean        tpdu_server_startup(gint port, GKeyFile *ini_file);
void            tpdu_server_shutdown();


gint
main(gint argc, gchar *argv[])
{
  GOptionContext *context;
  GError *error = NULL;
  gchar *log_path;
  gint listen_port;

  setlocale(LC_ALL, "");

  context = g_option_context_new("- BytePay TPDU 代理");
  g_option_context_add_main_entries(context, entries, NULL);
  if (!g_option_context_parse(context, &argc, &argv, &error))
    {
      g_print("解析命令行错误: %s\n", error->message);
      return 1;
    }
  if (!tpdu_read_inifile())
    return 1;

  log_path = g_key_file_get_string(ini_file, "SERVER", "log_path", &error);
  if (!log_path)
    {
      g_warning("配置文件中没有配置日志文件路径，请配置.");
      return 1;
    }
  g_log_set_default_handler(tpdu_log_handler, log_path);

  listen_port = g_key_file_get_integer(ini_file, "SERVER",
                                       "listen_port", &error);
  if (listen_port == 0)
    {
      if (error != NULL)
        {
          g_warning("Read Server listen_port error: %s",
                    error->message);
          return 1;
        }
      listen_port = 5000;
    }
  if (!tpdu_server_startup(listen_port, ini_file))
    {
      g_warning("启动网络服务器失败.");
      return 1;
    }
  main_loop = g_main_loop_new(NULL, FALSE);
  g_main_loop_run(main_loop);
  g_main_loop_quit(main_loop);
  tpdu_server_shutdown();

  return 0;
}
